package main

import (
	"context"
	"fmt"
	"github.com/spf13/viper"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"log"
	blobpb "serve/blob/api/gen/v1"
	"serve/blob/blob"
	"serve/blob/cos"
	"serve/blob/dao"
	"serve/settings"
	"serve/shared/server"
)

func main() {
	err := settings.Init()
	if err != nil {
		log.Fatalf(" settings.Init() %v", err)
	}

	logger, err := server.NewZapLogger()
	if err != nil {
		log.Fatalf("cannot create logger err %v", err)
	}

	c := context.Background()            // 建立一个content
	MongoClient, err := mongo.Connect(c, // 创建mongo连接
		options.Client().ApplyURI(fmt.Sprintf("mongodb://%s:%s@%s:%d",
			viper.GetString("mongodb.user"),
			viper.GetString("mongodb.password"),
			viper.GetString("mongodb.host"),
			viper.GetInt("mongodb.port"),
		)))

	if err != nil {
		logger.Fatal("mongo.Connect err", zap.Error(err))
	}

	service, err := cos.NewService(
		viper.GetString("cos.addr"),
		viper.GetString("cos.secID"),
		viper.GetString("cos.secKey"),
	)
	if err != nil {
		logger.Fatal("cos.Connect err", zap.Error(err))
	}

	err = server.RunGRPCServer(&server.GrpcConfig{
		Name: "blob",
		Addr: viper.GetInt("blob.srv.port"),
		RegisterFunc: func(server *grpc.Server) {
			blobpb.RegisterBlobServiceServer(server, &blob.Service{ // 注册trip的Server
				Logger:  logger, // 将日志传入Server
				Mongo:   dao.NewMongo(MongoClient.Database(viper.GetString("mongodb.dbname"))),
				Storage: service,
			})
		},
		Logger: logger,
	})

	if err != nil {
		logger.Fatal(" server.RunGRPCServer()", zap.Error(err))
	}
}
